<template>
  <div class="material-catalog">
    <div class="page-header">
      <div class="header-title">
        <h2>物料分类管理</h2>
        <el-tag type="info">管理物料和产品的分类目录</el-tag>
      </div>
    </div>

    <el-card class="table-card">
      <div class="table-toolbar">
        <div class="left-section">
          <el-button 
            :type="isExpanded ? 'primary' : 'default'" 
            class="expand-button" 
            @click="handleExpandAll"
          >
            <el-icon><ArrowDown v-if="isExpanded" /><ArrowRight v-else /></el-icon>
            {{ isExpanded ? '折叠全部' : '展开全部' }}
          </el-button>
          <el-button type="success" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
        <div class="right-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索分类名称..."
            class="search-input"
            clearable
            @clear="handleSearch"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <el-table
        ref="tableRef"
        :data="filteredTableData"
        border
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column prop="classifyName" label="分类名称" min-width="260">
          <template #default="{ row }">
            <span :style="{ paddingLeft: row.level ? '20px' : '0' }">
              <el-icon v-if="!row.children || !row.children.length"><Document /></el-icon>
              <el-icon v-else><Folder /></el-icon>
              {{ row.classifyName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderById" label="排序" width="100" align="center" />
        <el-table-column prop="materialName" label="物料/产品" min-width="180" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" effect="plain">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button link type="primary" @click.stop="handleEdit(row)">
                <el-icon><Edit /></el-icon>修改
              </el-button>
              <el-button link type="success" @click.stop="handleAdd(row)">
                <el-icon><Plus /></el-icon>新增
              </el-button>
              <el-button 
                link 
                type="danger" 
                @click.stop="handleDelete(row)"
                :disabled="row.children && row.children.length > 0"
                v-if="row.parentId"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增分类对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="addDialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="父分类" prop="parentId">
          <el-input v-model="addForm.parentName" disabled />
        </el-form-item>
        <el-form-item label="分类名称" prop="classifyName">
          <el-input v-model="addForm.classifyName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderById">
          <el-input-number v-model="addForm.orderById" :min="1" />
        </el-form-item>
        <el-form-item label="物料/产品" prop="materialType">
          <el-radio-group v-model="addForm.materialType">
            <el-radio :label="1">物料</el-radio>
            <el-radio :label="2">产品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 修改分类对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改分类"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="父分类" prop="parentId">
          <el-input v-model="editForm.parentName" disabled />
        </el-form-item>
        <el-form-item label="分类名称" prop="classifyName">
          <el-input v-model="editForm.classifyName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderById">
          <el-input-number v-model="editForm.orderById" :min="1" />
        </el-form-item>
        <el-form-item label="物料/产品" prop="materialType">
          <el-radio-group v-model="editForm.materialType">
            <el-radio :label="1">物料</el-radio>
            <el-radio :label="2">产品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { 
  ArrowDown, 
  ArrowRight,
  Edit,
  Plus,
  Delete,
  Search,
  Refresh,
  Document,
  Folder
} from '@element-plus/icons-vue'
import http from '@/api/http'

interface MaterialCatalog {
  id: number
  classifyName: string
  orderById: number
  materialName: string | null
  status: number
  createTime: Date
  parentId: number
  level?: number
  children?: MaterialCatalog[]
}

// 定义表单接口
interface AddForm {
  parentId: number | null
  parentName: string
  classifyName: string
  createTime: Date
  orderById: number
  materialType: number
  status: number
}

const tableData = ref<MaterialCatalog[]>([])
const tableRef = ref()
const isExpanded = ref(false)
const searchQuery = ref('')

// 搜索过滤
const filteredTableData = computed(() => {
  if (!searchQuery.value) return tableData.value
  
  const search = searchQuery.value.toLowerCase()
  const filterTree = (nodes: MaterialCatalog[]): MaterialCatalog[] => {
    return nodes.filter(node => {
      const matches = node.classifyName.toLowerCase().includes(search) ||
                     (node.materialName && node.materialName.toLowerCase().includes(search))
      
      if (node.children && node.children.length) {
        const filteredChildren = filterTree(node.children)
        if (filteredChildren.length) {
          node.children = filteredChildren
          return true
        }
      }
      
      return matches
    })
  }
  
  return filterTree([...tableData.value])
})

// 处理搜索
const handleSearch = () => {
  if (searchQuery.value) {
    isExpanded.value = true
  } else {
    isExpanded.value = false
  }
}

// 处理展开/折叠
const handleExpandAll = () => {
  isExpanded.value = !isExpanded.value
  nextTick(() => {
    if (tableRef.value) {
      const rows = tableRef.value.data || []
      rows.forEach((row: MaterialCatalog) => {
        tableRef.value.toggleRowExpansion(row, isExpanded.value)
        if (row.children && row.children.length > 0) {
          toggleChildren(row.children, isExpanded.value)
        }
      })
    }
  })
}

// 递归处理子节点的展开/折叠
const toggleChildren = (children: MaterialCatalog[], expanded: boolean) => {
  children.forEach(child => {
    if (tableRef.value) {
      tableRef.value.toggleRowExpansion(child, expanded)
      if (child.children && child.children.length > 0) {
        toggleChildren(child.children, expanded)
      }
    }
  })
}

// 刷新数据
const handleRefresh = () => {
  show()
  ElMessage.success('数据已刷新')
}

// 处理行点击
const handleRowClick = (row: MaterialCatalog) => {
  if (!row || typeof row.id !== 'number') return
  
  if (tableRef.value) {
    tableRef.value.toggleRowExpansion(row)
  }
}

// 表单校验规则
const formRules = {
  classifyName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  orderById: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ],
  materialType: [
    { required: true, message: '请选择物料/产品类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择启用状态', trigger: 'change' }
  ]
}

// 新增对话框相关
const addDialogVisible = ref(false)
const addDialogTitle = ref('新增分类')
const addFormRef = ref<FormInstance>()
const addForm = ref<AddForm>({
  parentId: null,
  parentName: '',
  classifyName: '',
  createTime: new Date(),
  orderById: 1,
  materialType: 1,
  status: 1
})

// 修改对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref({
  id: null as number | null,
  parentId: null as number | null,
  parentName: '',
  classifyName: '',
  orderById: 1,
  materialType: 1,
  status: 1
})

// 打开新增对话框
const handleAdd = (row: MaterialCatalog) => {
  addForm.value = {
    parentId: row.id,
    parentName: row.classifyName,
    classifyName: '',
    createTime: new Date(),
    orderById: 1,
    materialType: 1,
    status: 1
  }
  addDialogTitle.value = `新增 ${row.classifyName} 的子分类`
  addDialogVisible.value = true
}

// 打开修改对话框
const handleEdit = (row: MaterialCatalog) => {
  editForm.value = {
    id: row.id,
    parentId: row.parentId,
    parentName: row.parentId ? tableData.value.find(item => item.id === row.parentId)?.classifyName || '' : '根分类',
    classifyName: row.classifyName,
    orderById: row.orderById,
    materialType: row.materialName === '产品' ? 2 : 1,
    status: row.status
  }
  editDialogVisible.value = true
}

// 提交新增
const handleAddSubmit = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await http.post('/api/MaterialCatalogs/Add', {
          parentId: addForm.value.parentId,
          classifyName: addForm.value.classifyName,
          orderById: addForm.value.orderById,
          materialName: addForm.value.materialType === 1 ? '物料' : '产品',
          status: addForm.value.status,
          createTime: addForm.value.createTime.toISOString()
        })

        if (response.success) {
          ElMessage.success(response.message)
          addDialogVisible.value = false
          show() // 刷新数据
        } else {
          ElMessage.error(response.message)
        }
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '添加失败')
      }
    }
  })
}

// 提交修改
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await http.post('/api/MaterialCatalogs/Update', {
          id: editForm.value.id,
          parentId: editForm.value.parentId,
          classifyName: editForm.value.classifyName,
          orderById: editForm.value.orderById,
          materialName: editForm.value.materialType === 1 ? '物料' : '产品',
          status: editForm.value.status
        })

        if (response.success) {
          ElMessage.success(response.message)
          editDialogVisible.value = false
          show() // 刷新数据
        } else {
          ElMessage.error(response.message)
        }
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '修改失败')
      }
    }
  })
}

const handleDelete = async (row: MaterialCatalog) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该分类下还有子分类，无法删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除该分类吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await http.post('/api/MaterialCatalogs/Delete', {
      id: row.id
    })

    if (response.success) {
      ElMessage.success(response.message)
      show() // 刷新数据
    } else {
      ElMessage.error(response.message)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const show = async () => {
  try {
    const response = await http.get('/api/MaterialCatalogs/GetTree')
    if (Array.isArray(response)) {
      tableData.value = response
      nextTick(() => {
        if (tableRef.value) {
          const rows = tableRef.value.data || []
          rows.forEach((row: MaterialCatalog) => {
            tableRef.value.toggleRowExpansion(row, isExpanded.value)
            if (row.children && row.children.length > 0) {
              toggleChildren(row.children, isExpanded.value)
            }
          })
        }
      })
    }
  } catch (error: any) {
    ElMessage.error('获取数据失败：' + error.message)
  }
}

onMounted(() => {
  isExpanded.value = false
  show()
})
</script>

<style scoped>
.material-catalog {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.table-card {
  background: #fff;
  border-radius: 4px;
}

.table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  gap: 8px;
}

.right-section {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.expand-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

:deep(.el-table) {
  margin-top: 8px;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-button--link) {
  height: 28px;
  padding: 0 8px;
  display: inline-flex;
  align-items: center;
}

:deep(.el-button--link .el-icon) {
  margin-right: 4px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-button-group) {
  display: inline-flex;
  gap: 8px;
}
</style>
  